import { ElMessage } from "element-plus";

//建立文件applycation的数据集
const applycationType = {
  txt: "text/plain",
  doc: "application/msword",
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  pdf: "application/pdf",
  xls: "application/vnd.ms-excel",
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  xlsm: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  xlm: "application/vnd.ms-excel",
  ppt: "application/vnd.ms-powerpoint",
  pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  wps: "application/vnd.ms-works",
  tgz: "application/x-compressed",
  tar: "application/x-tar",
  zip: "application/zip",
  bmp: "image/bmp",
  gif: "image/gif",
  jpe: "image/jpeg",
  jpeg: "image/jpeg"
};

export default function (res, fileName, type = "blob") {
  //fileName  test.txt
  //res type=='blob' ? 后台传递的文件流 : 直接下载的链接
  if (!fileName) {
    ElMessage({
      message: "文件名不存在",
      type: "warning"
    });
    return;
  }
  //根据文件名获取文件格式
  let nameStr = fileName.split(".");
  let fileType = nameStr[nameStr.length - 1];
  fileName = nameStr[0];
  //获取该文件的application
  let fileApplycation = applycationType[fileType];
  //获取时间戳
  let timestap = Date.now();

  try {
    const link = document.createElement("a");
    if (type == "blob") {
      const data = new Blob([res], {
        type: fileApplycation
      });
      link.href = window.URL.createObjectURL(data);
    } else {
      link.href = res;
    }

    link.style.display = "none";
    //重命名文件=文件名_时间.类型
    link.download = fileName + "_" + timestap + "." + fileType;
    document.body.appendChild(link);
    link.click();
    // 使用完后再删除释放
    if (type == "blob") {
      window.URL.revokeObjectURL(link.href);
    }

    document.body.removeChild(link);
  } catch (e) {
    ElMessage({
      message: "下载文件出错",
      type: "warning"
    });
  }
}
